package com.imot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.imot.handler.ImotExciption;
import com.imot.mapper.EmaRecordMapper;
import com.imot.mapper.TargetParametersMapper;
import com.imot.pojo.entity.*;
import com.imot.pojo.vo.*;
import com.imot.response.Result;
import com.imot.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName: FaultDiagnosisServiceImpl
 * Description:
 * date: 2023/11/16 14:24
 *
 * @author imot-jiah.wang
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FaultDiagnosisServiceImpl implements FaultDiagnosisService {

    private final IEmaRecordShortTermService emaRecordShortTermService;
    private final IEmaRecordMidTermService emaRecordMidTermService;
    private final IEmaRecordExtendedTermService emaRecordExtendedTermService;
    private final IEmaRecordLongTermService emaRecordLongTermService;
    private final IEmaRecordService emaRecordService;
    private final EmaRecordMapper emaRecordMapper;
    private final IDictService dictService;
    private final ITargetParametersService targetParametersService;
    private final TargetParametersMapper targetParametersMapper;
    private final IEmaErrorRecordService emaErrorRecordService;
    private final EmaRecordMapper recordMapper;
    private final IErrorThresholdsService errorThresholdsService;

    @Override
    public Result faultDiagnosisService(String parameterName, LocalDateTime startTime, LocalDateTime endTime) {
        List<FaultDiagnosisVo> faultDiagnosisVos = new ArrayList<>();
        // 创建并填充第一个 FaultDiagnosisVo 对象
        FaultDiagnosisVo faultDiagnosisVo1 = new FaultDiagnosisVo();
        List<Map<Object, Object>> list1 = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Map<Object, Object> map = new HashMap<>();
            map.put("time", LocalDateTime.now().plusHours(i)); // 增加不同的小时数
            map.put("value", 100.0f + i * 10); // 示例值
            list1.add(map);
        }
        faultDiagnosisVo1.setList(list1);
        faultDiagnosisVo1.setUpperThreshold(150.0f);
        faultDiagnosisVo1.setLowerThreshold(100.0f);
        faultDiagnosisVo1.setParameterName("参数1");

        // 创建并填充第二个 FaultDiagnosisVo 对象
        FaultDiagnosisVo faultDiagnosisVo2 = new FaultDiagnosisVo();
        List<Map<Object, Object>> list2 = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Map<Object, Object> map = new HashMap<>();
            map.put("time", LocalDateTime.now().plusHours(3 + i)); // 再增加小时数
            map.put("value", 200.0f + i * 20); // 示例值
            list2.add(map);
        }
        faultDiagnosisVo2.setList(list2);
        faultDiagnosisVo2.setUpperThreshold(200.0f);
        faultDiagnosisVo2.setLowerThreshold(150.0f);
        faultDiagnosisVo2.setParameterName("参数2");

// 将对象添加到列表
        faultDiagnosisVos.add(faultDiagnosisVo1);
        faultDiagnosisVos.add(faultDiagnosisVo2);

        Duration duration = Duration.between(startTime, endTime);
        long hours = duration.toHours();

        LambdaQueryWrapper<Dict> dictLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dictLambdaQueryWrapper.ge(Dict::getId,30000);
        dictLambdaQueryWrapper.lt(Dict::getId,40000);
        if (hours<1){
            dictLambdaQueryWrapper.eq(Dict::getValue,1);
        }
        if (hours<12&&hours>=1){
            dictLambdaQueryWrapper.eq(Dict::getValue,2);
        }
        if (hours<144&&hours>=12){
            dictLambdaQueryWrapper.eq(Dict::getValue,3);
        }
        if (hours<1728&&hours>=144) {
            dictLambdaQueryWrapper.eq(Dict::getValue, 4);
        }
        if (hours<20736&&hours>=1728){
            dictLambdaQueryWrapper.eq(Dict::getValue,5);
        }
        Dict dict = dictService.getOne(dictLambdaQueryWrapper);
        String tableName = dict.getName();

        LambdaQueryWrapper<Dict> dictLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        dictLambdaQueryWrapper1.gt(Dict::getId,10000);
        dictLambdaQueryWrapper1.lt(Dict::getId,20000);
        dictLambdaQueryWrapper1.eq(Dict::getName,parameterName);
        Dict dict1 = dictService.getOne(dictLambdaQueryWrapper1);
        if (dict1==null)throw new ImotExciption(500,"字典中查不到该参数");
        String name = dict1.getName();
        List<Map<String,Object>> list = emaRecordMapper.getDateWave(startTime,endTime,name,tableName);

        LambdaQueryWrapper<Dict> dictLambdaQueryWrapper2 = new LambdaQueryWrapper<>();
        dictLambdaQueryWrapper2.gt(Dict::getId,40000);
        dictLambdaQueryWrapper2.lt(Dict::getId,50000);
        dictLambdaQueryWrapper2.eq(Dict::getDictCode,parameterName);

        List<Dict> list3 = dictService.list(dictLambdaQueryWrapper2);
        if (list3==null||list3.size()==0)throw new ImotExciption(500,"参数传入异常，字典表中没有该参数");
        FaultDiagnosisVo faultDiagnosisVo = new FaultDiagnosisVo();
        if (list3.size()==1){
            Dict dict2 = list3.get(0);
            String name1 = dict2.getName();
            Float target = targetParametersMapper.getParametersUD(name1);
            faultDiagnosisVo.setUpperThreshold(target);
        }
        if (list3.size()==2){
            Dict dict2 = list3.get(0);
            String name1 = dict2.getName();
            Float target = targetParametersMapper.getParametersUD(name1);
            faultDiagnosisVo.setUpperThreshold(target);
            Dict dict3 = list3.get(1);
            String name2 = dict3.getName();
            Float targe2 = targetParametersMapper.getParametersUD(name2);
            faultDiagnosisVo.setLowerThreshold(targe2);
        }

        return Result.success(faultDiagnosisVos);
    }

    //获取一个时间长度小时计算


    @Override
    public Result getDiagnosisStart(MultipartFile file) {
        DiagnosisStartvO diagnosisStartvO = new DiagnosisStartvO();
        return Result.success();
    }

    @Override
    public Result confirmErrorCondition(Integer id) {

//        LambdaQueryWrapper<Dict> dictLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        dictLambdaQueryWrapper.gt(Dict::getId,20000);
//        dictLambdaQueryWrapper.lt(Dict::getId,30000);
//        dictLambdaQueryWrapper.eq(Dict::getName,faultRight);
//        Dict dict1 = dictService.getOne(dictLambdaQueryWrapper);
//        if (dict1==null)throw new ImotExciption(500,"参数错误，找不到该确认类型");
//        String value1 = dict1.getValue()+"";
//
//
//        EmaErrorRecord errorRecord = new EmaErrorRecord();
//        errorRecord.setId(id);
//        errorRecord.setErrorHandledFlag(value1);
//        emaErrorRecordService.updateById(errorRecord);

        ExceptionDetailVo exceptionDetailVo = new ExceptionDetailVo();
        EmaErrorRecord emaErrorRecord = emaErrorRecordService.getById(id);

        if (emaErrorRecord == null) throw new ImotExciption(500, "入参id错误，找不到该id");

        Integer emaRecordId = emaErrorRecord.getEmaRecordId();
        Integer targetParametersId = emaErrorRecord.getTargetParametersId();


        String exceptionParameters = emaErrorRecord.getErrorParameters();
        String[] pairs = exceptionParameters.split("。\\s*");

        List<String> parameters = new ArrayList<>();
        List<String> values = new ArrayList<>();
        ArrayList<String> exceptionParameterList = new ArrayList<>();
        HashMap<String, String> exceptionParameterHashMap = new HashMap<>();

        for (String pair : pairs) {
            if (!pair.isEmpty()) {
                // 使用“：”分割每对参数和值
                String[] parts = pair.split("：");
                parameters.add(parts[0]); // 添加参数名称
                values.add(parts[1]); // 添加值
            }
        }

        for (int i = 0; i < parameters.size(); i++) {
            exceptionParameterHashMap.put(parameters.get(i), values.get(i));
        }

        log.info("------------------{}", parameters);
        ArrayList<DetailVo> detailVos = new ArrayList<>();
        for (String parameter : parameters) {
            LambdaQueryWrapper<Dict> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Dict::getDictCode, parameter);
            queryWrapper.ge(Dict::getId, 10000);
            queryWrapper.lt(Dict::getId, 20000);
            Dict dict = dictService.getOne(queryWrapper);

            String unit = dict.getUnit();
            String value = exceptionParameterHashMap.get(parameter);
            String exceptionParameter = parameter + ":" + value + unit;
            exceptionParameterList.add(exceptionParameter);

            String name = dict.getName();
            String name1 = convertName(name);
            log.info("~~~~~~~~~~~~~~~{}", name1);
            List<Map<Object, Object>> valueList = recordMapper.getTheRecordsAroundId(emaRecordId, name1);
            Map<LocalDateTime, Float> hashMap = new HashMap<>();
            for (Map<Object, Object> map : valueList) {
                LocalDateTime time = (LocalDateTime) map.get("time");
                Float theValue = (Float) map.get("value");
                hashMap.put(time, theValue);
            }
            DetailVo detailVo = new DetailVo();
            detailVo.setWaveValues(valueList);

            LambdaQueryWrapper<ErrorThresholds> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ErrorThresholds::getErrorParameter, parameter);
            wrapper.eq(ErrorThresholds::getEmaErrorRecordId, id);
            ErrorThresholds exceptionThresholds = errorThresholdsService.getOne(wrapper);
            if (exceptionThresholds == null) throw new ImotExciption(500, "上下阈值出现错误，请联系管理员");
            Float upperThreshold = exceptionThresholds.getUpperThreshold();
            Float lowerThreshold = exceptionThresholds.getLowerThreshold();
            detailVo.setLowerThreshold(lowerThreshold);
            detailVo.setUpperThreshold(upperThreshold);
            detailVo.setParameter(parameter + unit);
            detailVos.add(detailVo);
            exceptionDetailVo.setWaveExceptionValueList(detailVos);
        }
        return Result.success(detailVos);
    }

    @Override
    public Result carryOutLiveCheckup() {
        LambdaQueryWrapper<EmaErrorRecord> emaErrorRecordLambdaQueryWrapper = new LambdaQueryWrapper<>();
        emaErrorRecordLambdaQueryWrapper.eq(EmaErrorRecord::getErrorHandledFlag,0);
        List<EmaErrorRecord> list = emaErrorRecordService.list(emaErrorRecordLambdaQueryWrapper);
        return Result.success(list);
    }

    @Override
    public Result getHistoryFault(LocalDateTime startTime, LocalDateTime endTime, Integer page, Integer limit, String faultType, String deviceName) {
        List<FaultInfoVo> emaErrorRecords = new ArrayList<>();
        return Result.success(emaErrorRecords);
    }

    @Override
    public Result getHistoricalFaultDiagnosisReports(Integer errorId) {
        EmaErrorRecord byId = emaErrorRecordService.getById(errorId);
        FaultVo faultVo = new FaultVo();
        return Result.success(faultVo);
    }

    @Override
    public Result confirmFaultReport(String reportName) {
        return Result.success();
    }

    @Override
    public Result confirmTopFaultStatus() {
        return null;
    }

    public String convertName(String name) {
        StringBuilder convertedName = new StringBuilder();

        for (char ch : name.toCharArray()) {
            if (Character.isUpperCase(ch)) {
                // 如果字符是大写字母，在前面添加横杠并转换为小写
                convertedName.append('_').append(Character.toLowerCase(ch));
            } else {
                // 如果不是大写字母，直接添加字符
                convertedName.append(ch);
            }
        }

        return convertedName.toString();
    }
}

